﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MarchEstate.Manager.BusinesEntity;
using Newtonsoft.Json;
using System.Data;
using CoreFrame.Core.Orm;
using System.Collections;

public class RoomController : AbstractJqueryController
{
    #region 得到基本类型
    /// <summary>
    /// 得到基本类型
    /// </summary>
    public void GetBaseData()
    {
        int useType = Convert.ToInt32(ParamsData["type"]);
        AbstractBaseData baseData = NewObject<AbstractBaseData>();
        DataTable baseDataList = baseData.GetBaseDicData(useType);
        //DataRow dr = baseDataList.NewRow();
        //dr["Name"] = "全部类型";
        //dr["Code"] = -1;
        //baseDataList.Rows.Add(dr);
        TxtJson = JavaScriptConvert.SerializeObject(baseDataList);
    }
    #endregion

    #region 房屋类型（除门面）
    /// <summary>
    /// 房屋类型（除门面）
    /// </summary>
    public void GetRoomType()
    {
        TxtJson = "[{\"Code\":4,\"Name\":\"居住\"},{\"Code\":5,\"Name\":\"住改商\"}]";
    }
    #endregion

    #region  管理区域

    #region 得到所有的管理区域
    /// <summary>
    /// 得到所有的管理区域
    /// </summary>
    public void GetAreaList()
    {
        AbstractArea area = NewObject<AbstractArea>();
        List<AbstractArea> areaList = area.GetAreaList();
        TxtJson = ListToJson(areaList);
    }
    #endregion

    #region 得到所有的管理区域的Code Name
    /// <summary>
    /// 得到所有的管理区域
    /// </summary>
    public void GetCombAreaList()
    {
        AbstractArea area = NewObject<AbstractArea>();
        DataTable areaList = area.GetAreaFieldList();
        //DataRow dr = areaList.NewRow();
        //dr["AreaName"] = "所有管理区";
        //dr["AreaCode"] = -1;
        //areaList.Rows.Add(dr);
        TxtJson = JavaScriptConvert.SerializeObject(areaList);
    }
    #endregion

    #region 添加管理区域
    /// <summary>
    /// 添加管理区域
    /// </summary>
    public void AddArea()
    {
        try
        {
            AbstractArea area = NewObject<AbstractArea>();
            GetModelToForm<AbstractArea>(area);
            string type = FormData["type"];
            if (area.Save(type))
            {
                TxtJson = ReturnSuccess("维护管理区域成功！");
            }
            else
            {
                TxtJson = ReturnSuccess("维护管理区域失败！");
            }
        }
        catch (Exception err)
        {
            TxtJson = ReturnError(err.Message);
        }
    }
    #endregion

    #region 删除管理区域
    /// <summary>
    /// 删除管理区域
    /// </summary>
    public void DelArea()
    {
        try
        {
            string areaCode = Convert.ToString(ParamsData["areaCode"]);
            AbstractArea area = NewObject<AbstractArea>();
            if (area.Delete(areaCode))
            {
                TxtJson = ReturnSuccess("删除管理区域成功！");
            }
            else
            {
                TxtJson = ReturnSuccess("删除管理区域失败！");
            }
        }
        catch (Exception ex)
        {
            TxtJson = ReturnError(ex.Message);
        }
    }
    #endregion  


    #endregion 

    #region  楼宇

    #region 得到楼宇
    /// <summary>
    /// 得到楼宇
    /// </summary>
    public void GetBuildingList()
    {
        string areaCode = Convert.ToString(ParamsData["AreaCode"]);
        AbstractBuilding building = NewObject<AbstractBuilding>();
        List<AbstractBuilding> BuildingList = building.GetBuildingList(areaCode);
        TxtJson = ListToJson(BuildingList);
    }
    #endregion

    #region 得到楼宇的Code Name
    /// <summary>
    /// 得到楼宇的Code Name
    /// </summary>
    public void GetBuildingFieldList()
    {
        string areaCode = Convert.ToString(ParamsData["AreaCode"]);
        AbstractBuilding building = NewObject<AbstractBuilding>();
        DataTable buildingList = building.GetBuildingFieldList(areaCode);
        //DataRow dr = buildingList.NewRow();
        //dr["BuildingName"] = "所有楼宇";
        //dr["BuildingCode"] = -1;
        //buildingList.Rows.Add(dr);

        TxtJson = JavaScriptConvert.SerializeObject(buildingList);
    }
    #endregion

    #region 得到楼宇的单元（combox）
    /// <summary>
    /// 得到楼宇的单元
    /// </summary>
    public void GetUnitComArray()
    {
        string buildingCode = Convert.ToString(ParamsData["BuildingCode"]);
        AbstractBuilding building = NewObject<AbstractBuilding>();
        AbstractBuilding buildingObject = building.GetBuilding(buildingCode);
        string unit = buildingObject.Unit;
        string[] unitarray = unit.Split(new char[] { ',' });
        string json = "";
        for (var i = 0; i < unitarray.Length; i++)
        {
            json += "{\"Code\":\"" + unitarray[i] + "\"},";
        }
        json = json.Remove(json.LastIndexOf(","));
        TxtJson = "[" + json + "]";
    }
    #endregion

    #region 得到楼宇的单元
    /// <summary>
    /// 得到楼宇的单元
    /// </summary>
    public void GetCellArray()
    {
        string buildingCode = Convert.ToString(ParamsData["BuildingCode"]);
        AbstractBuilding building = NewObject<AbstractBuilding>();
        AbstractBuilding buildingObject = building.GetBuilding(buildingCode);
        string cell = buildingObject.Unit;
        int floorNum = buildingObject.FloorNum;
        string[] cellarray = cell.Split(new char[]{','});
        string roomlist = "";
        for (var i = 0; i < cellarray.Length; i++)
        {
            roomlist += "{\"CellNum\":\"" + cellarray[i] + "\",\"roomBegin\":\"\",\"roomEnd\":\"\",\"FloorNum\":\"" + floorNum + "\"},";
        }
        roomlist = roomlist.Remove(roomlist.LastIndexOf(","));
        roomlist = "{\"total\":" + cellarray.Length + ",\"rows\": [" + roomlist + "]}";
        TxtJson = ReturnSuccess("", roomlist);
    }
    #endregion

    #region 添加楼宇
    /// <summary>
    /// 添加楼宇
    /// </summary>
    public void AddBuilding()
    {
        try
        {
            AbstractBuilding building = NewObject<AbstractBuilding>();
            building.AreaCode = Convert.ToString(FormData["AreaCode"]);
            GetModelToForm<AbstractBuilding>(building);
            string type = FormData["type"];
            if (building.Save(type))
            {
                TxtJson = ReturnSuccess("维护楼宇成功！");
            }
            else
            {
                TxtJson = ReturnSuccess("维护楼宇失败！");
            }
        }
        catch(Exception err)
        {
             TxtJson = ReturnError(err.Message);
        }
    }
    #endregion

    #region 删除楼宇
    /// <summary>
    /// 删除楼宇
    /// </summary>
    public void DelBuilding()
    {
        string buildingCode = Convert.ToString(ParamsData["buildingCode"]);
        AbstractBuilding building = NewObject<AbstractBuilding>();
        if (building.Delete(buildingCode))
        {
            TxtJson = ReturnSuccess("删除楼宇成功！");
        }
        else
        {
            TxtJson = ReturnSuccess("删除楼宇失败！");
        }
    }
    #endregion  

    #endregion 

    #region  房间

    #region 得到房间
    /// <summary>
    /// 得到房间
    /// </summary>
    public void GetRoomList()
    {
        AbstractRoom room = NewObject<AbstractRoom>();
        Hashtable hash = new Hashtable();

        int pagesize = Convert.ToInt32(ParamsData["page"]);
        int rows = Convert.ToInt32(ParamsData["rows"]);
        if (ParamsData.ContainsKey("AreaCode"))
        {
            hash.Add("areacode", ParamsData["AreaCode"]);
        }
        else
        {
            hash.Add("areacode", "");
        }
        if (ParamsData.ContainsKey("BuildingCode"))
        {
            hash.Add("buildingCode", ParamsData["BuildingCode"]);
        }
        else
        {
            hash.Add("buildingCode", "");
        }
        if (ParamsData.ContainsKey("UseType"))
        {
            hash.Add("use_type", ParamsData["UseType"]);
        }
        else
        {
            hash.Add("use_type", "");
        }
        if (ParamsData.ContainsKey("RoomNumber"))
        {
            hash.Add("roomname", ParamsData["RoomNumber"]);
        }
        else
        {
            hash.Add("roomname", "");
        }
        //是否出售
        if (ParamsData.ContainsKey("SafeFlag"))
        {
            hash.Add("saleflag", ParamsData["SafeFlag"]);
        }
        else
        {
            hash.Add("saleflag", "-1");
        }
        PageInfo page = new PageInfo(rows, pagesize);

        DataTable dtRoomList = room.GetRoomList(hash, page);

        TxtJson = DataTableToJson(dtRoomList,page.totalRecord);
    }
    #endregion

    #region 添加房间
    /// <summary>
    /// 房间
    /// </summary>
    public void AddRoom()
    {
        try
        {
            string buildingCode = Convert.ToString(FormData["BuildingCode"]);
            AbstractRoom room = NewObject<AbstractRoom>();
            GetModelToForm<AbstractRoom>(room);
            room.BuildingCode = buildingCode;

            if (room.Save())
            {
                TxtJson = ReturnSuccess("维护房间成功！");
            }
            else
            {
                TxtJson = ReturnSuccess("维护房间失败！");
            }
        }
        catch (Exception err)
        {
            TxtJson = ReturnError(err.Message);
        }
    }
    #endregion  

    #region 批量添加房间
    /// <summary>
    /// 批量添加房间
    /// </summary>
    public void BatchAddRoom()
    {
        try
        {
            string unit = "";
            int roomBegin;
            int roomEnd;
            string data = Convert.ToString(ParamsData["data"]);
            string buildingCode = Convert.ToString(ParamsData["BuildingCode"]);
            string areaCode = Convert.ToString(ParamsData["AreaCode"]);
            string rule = Convert.ToString(ParamsData["Rule"]);//1区域 2大楼 3楼层 4单元 5房间号 
            int floorNum = Convert.ToInt32(ParamsData["FloorNum"]);
            List<AbstractRoom> roomFloorList = new List<AbstractRoom>();
            List<AbstractRoom> roomNumList = new List<AbstractRoom>();
            //区域
            if (rule.IndexOf("[1]") != -1)
            {   
                rule=rule.Replace("[1]", areaCode);
            }
            //大楼
            if (rule.IndexOf("[2]") != -1)
            {
                rule=rule.Replace("[2]", buildingCode);
            }
            //楼层
            if (rule.IndexOf("[3]") != -1)
            {
                for (int j = 1; j <= floorNum; j++)
                {
                    AbstractRoom room = NewObject<AbstractRoom>();
                    room.AreaCode = areaCode;
                    room.BuildingCode = buildingCode;
                    room.FloorNum = j;
                    room.RoomNumber = rule.Replace("[3]", j.ToString().PadLeft(2,'0'));
                    roomFloorList.Add(room);
                }
            }
            else
            {
                AbstractRoom room = NewObject<AbstractRoom>();
                room.AreaCode = areaCode;
                room.BuildingCode = buildingCode;
                room.RoomNumber = rule;
                roomFloorList.Add(room);
            }

            //构造房间单元以及对应的房间号
            DataTable roomUnit = new DataTable();
            roomUnit.Columns.Add("Unit", System.Type.GetType("System.String"));
            roomUnit.Columns.Add("RoomBegin", System.Type.GetType("System.Int32"));
            roomUnit.Columns.Add("RoomEnd", System.Type.GetType("System.Int32"));
            Newtonsoft.Json.JavaScriptArray json = (Newtonsoft.Json.JavaScriptArray)JavaScriptConvert.DeserializeObject(data);
            for (int i = 0; i < json.Count; i++)
            {
                JavaScriptObject jsobj = (JavaScriptObject)json[i];
                DataRow dRow = roomUnit.NewRow();
                dRow["Unit"] = Convert.ToString(jsobj.ToList()[0].Value);
                dRow["RoomBegin"] = Convert.ToInt32(jsobj.ToList()[1].Value);
                dRow["RoomEnd"] = Convert.ToInt32(jsobj.ToList()[2].Value);
                roomUnit.Rows.Add(dRow);
            }
            
            //单元
            if (rule.IndexOf("[4]") != -1)
            {
                for (int i = 0; i < roomUnit.Rows.Count; i++)
                {
                     unit = roomUnit.Rows[i]["Unit"].ToString().Trim();
                     roomBegin = Convert.ToInt32(roomUnit.Rows[i]["RoomBegin"].ToString().Trim());
                     roomEnd = Convert.ToInt32(roomUnit.Rows[i]["RoomEnd"].ToString().Trim());
                     int beginLength = roomUnit.Rows[i]["RoomBegin"].ToString().Trim().Length;
                     int endLength = roomUnit.Rows[i]["RoomEnd"].ToString().Trim().Length;
                     int lenght = beginLength < endLength ? endLength : beginLength;
                    for (int j = 0; j < roomFloorList.Count; j++)
                    {
                        string num;
                        string temp;
                        temp = roomFloorList[j].RoomNumber.Replace("[4]", unit);
                        for (int k = roomBegin; k <= roomEnd; k++)
                        {
                            AbstractRoom room = NewObject<AbstractRoom>();
                            num = Convert.ToString(k).PadLeft(lenght, '0');
                            room.Unit = unit;
                            room.AreaCode = areaCode;
                            room.BuildingCode = buildingCode;
                            room.FloorNum = roomFloorList[j].FloorNum;
                            room.UseType =1;//商住
                            room.UseStatus = 1;//空置
                            room.RoomNumber = temp.Replace("[5]", num);
                            roomNumList.Add(room);
                        }
                    }
                }
            }
            else
            {

                     roomBegin = Convert.ToInt32(roomUnit.Rows[0]["RoomBegin"].ToString().Trim());
                     roomEnd = Convert.ToInt32(roomUnit.Rows[0]["RoomEnd"].ToString().Trim());
                     int beginLength = roomUnit.Rows[0]["RoomBegin"].ToString().Trim().Length;
                     int endLength = roomUnit.Rows[0]["RoomEnd"].ToString().Trim().Length;
                     int lenght = beginLength < endLength ? endLength : beginLength;
                    for (int j = 0; j < roomFloorList.Count; j++)
                    {
                        AbstractRoom tempRoom = roomFloorList[j];
                        string num;
                        string temp;
                        temp = roomFloorList[j].RoomNumber;
                        for (int k = roomBegin; k <= roomEnd; k++)
                        {
                            AbstractRoom room = NewObject<AbstractRoom>();
                            num = Convert.ToString(k).PadLeft(lenght, '0');
                              room.AreaCode = areaCode;
                            room.BuildingCode = buildingCode;
                            room.FloorNum = roomFloorList[j].FloorNum;
                            room.UseType = 1;//商住
                            room.UseStatus = 1;//空置
                            room.RoomNumber = temp.Replace("[5]", num);
                            roomNumList.Add(room);
                        }
                    }

            }
            AbstractRoom roomList = NewObject<AbstractRoom>();
            roomList.Save(roomNumList);
          
             TxtJson = ReturnSuccess("批量添加房间成功！");
 
        }
        catch (Exception err)
        {
            TxtJson = ReturnError(err.Message);
        }
    }
    #endregion  

    #region 删除房间
    /// <summary>
    /// 删除房间
    /// </summary>
    public void DelRoom()
    {
        string roomId = Convert.ToString(ParamsData["RoomId"]);
        AbstractRoom room = NewObject<AbstractRoom>();
        if (room.Delete(roomId))
        {
            TxtJson = ReturnSuccess("删除房间成功！");
        }
        else
        {
            TxtJson = ReturnSuccess("删除房间失败！");
        }
    }
    #endregion  

    #endregion

    #region 门面
   
    #region 门面
    /// <summary>
    /// 添加门面
    /// </summary>
    public void AddShop()
    {
        try
        {
            string data = Convert.ToString(ParamsData["data"]);
            string shopName = Convert.ToString(ParamsData["ShopName"]);
            decimal useArea = Convert.ToDecimal(ParamsData["UseArea"]);
            string memo = Convert.ToString(ParamsData["Memo"]);
            string shopId = Convert.ToString(ParamsData["ShopId"]);
            List<string> roomNumberList = new List<string>();
            List<string> roomIdList = new List<string>();
            AbstractShop shop = NewObject<AbstractShop>();
            Newtonsoft.Json.JavaScriptArray json = (Newtonsoft.Json.JavaScriptArray)JavaScriptConvert.DeserializeObject(data);

            for (int i = 0; i < json.Count; i++)
            {
                JavaScriptObject jsobj = (JavaScriptObject)json[i];
                for (int j = 0; j < jsobj.ToList().Count; j++)
                {   
                    if (jsobj.ToList()[j].Key == "RoomNumber")
                       roomNumberList.Add(jsobj.ToList()[j].Value.ToString());
                    if (jsobj.ToList()[j].Key == "RoomId")
                        roomIdList.Add(jsobj.ToList()[j].Value.ToString());
                }              
            }
            //保存门面
            shop.ShopId = shopId;
            shop.ShopName = shopName;
            shop.UseArea = useArea;
            shop.Memo = memo;
            shop.DeleteFlag = 0;
            bool shopEdit = shop.Save(roomIdList, roomNumberList);
            if (shopEdit == true)
            {
                TxtJson = ReturnSuccess("添加门面成功！");
            }
            else
            {
                TxtJson = ReturnSuccess("添加门面失败！");
            }

        }
        catch (Exception err)
        {
            TxtJson = ReturnError(err.Message);
        }
    }
    #endregion

    #region 得到门面绑定的房间
    /// <summary>
    /// 得到门面绑定的房间
    /// </summary>
    public void GetShopsRoom()
    {
        try
        {
            string shopid = Convert.ToString(ParamsData["ShopId"]);
            AbstractShop shop = NewObject<AbstractShop>();
            List<AbstractRoom> shopList = shop.GetShopsRoomList(shopid);
            if (shopList != null)
            {
                TxtJson = ListToJson(shopList);
            }
            else
            {
                TxtJson = "{\"total\":" + 0 + ",\"rows\": []}";
            }
         
        }
        catch (Exception err)
        {
            TxtJson = ReturnError(err.Message);
        }
    }
    #endregion

    #region 删除门面
    /// <summary>
    /// 删除门面
    /// </summary>
    public void DelShop()
    {
        string shopid = Convert.ToString(ParamsData["ShopId"]);
        AbstractShop shop = NewObject<AbstractShop>();
        if (shop.Delete(shopid))
        {
            TxtJson = ReturnSuccess("删除门面成功！");
        }
        else
        {
            TxtJson = ReturnSuccess("删除门面失败！");
        }
    }
    #endregion  

    #endregion

}
 
